<template>
  <a-select
    :placeholder="placeholder"
    show-search
    :filterOption="false"
    @focus="search = ''; pageNum = 1; getLabelList()"
    @search="searchData"
    @popupScroll="scroll"
    :loading="searchLoading"
    v-model="id"
    v-bind="options"
    @change="selectItem"
  >
    <a-select-option v-for="item in data" :value="item.code" :key="item.code">
      {{ item.name }}
    </a-select-option>
  </a-select>
</template>
<script>
import {tableMixins} from '@/utils/mixins'
import { getPageStoreList } from '@/api/store'
import {cloneDeep, debounce} from 'lodash'
export default {
  name: 'SelectStore',
  mixins: [tableMixins],
  props: {
    placeholder: {
      type: String,
      default: '请选择门店'
    },
    code: {
      type: String,
      default: ''
    },
    name: {
      type: String,
      default: ''
    },
    value: {
      type: [String, Number],
      default: undefined
    },
    options: {
      type: Object,
      default: () => ({})
    }
  },
  model: {
    prop: 'value',
    event: 'change'
  },
  data() {
    return {
      id: undefined,
      search: '',
      vendorCode: '',
      searchLoading: false,
      data: []
    }
  },
  created() {
    this.$watch('name', name => {
      this.name = name
      this.searchData(this.name)
    })
    this.$watch('value', value => {
      if (this.data.length > 0 && this.data.filter(e => e.code === value).length > 0) this.id = value
    })
    this.searchData = debounce(this.searchData, 800)
    this.$watch('code', vendorCode => {
      this.vendorCode = vendorCode
      this.id = undefined
    }, {immediate: true})
  },
  methods: {
    cloneDeep,
    searchData(search) {
      this.search = search
      this.pageNum = 1
      this.getLabelList()
    },
    scroll(e) {
      const {scrollHeight, scrollTop, clientHeight} = e.target
      if (scrollHeight - scrollTop === clientHeight) {
        if (this.data.length === this.total || this.searchLoading) return
        this.pageNum++
        this.getLabelList()
      }
    },
    selectItem(value) {
      const {name} = this.data.find(e => e.code === value)
      this.$emit('change', value, name)
    },
    getLabelList() {
      this.searchLoading = true
      getPageStoreList({
        search: this.search.trim(),
        pageSize: this.rowsNum,
        pageNo: this.pageNum
      }).then(res => {
        this.searchLoading = false
        const {items, rowCount} = res
        this.data = this.pageNum === 1 ? items : this.data.concat(items)
        this.id = this.value
        this.total = rowCount
      }).catch(() => this.searchLoading = false)
    }
  }
}
</script>
